import sys, os
import config
import queue

def startServer(blocking=False,port=8080):
	fakeQueue= queue.Queue()
	if blocking:
		from threaded import ServerThreaded
		s= ServerThreaded(porta=port,fakeQueue=fakeQueue)
	else:
		from nonblocking import ServerNonBlocking
		s= ServerNonBlocking(porta=port,fakeQueue=fakeQueue)
	s.ascolta()

if __name__ == "__main__":
	if len(sys.argv) > 1:
		configDir = os.path.realpath(sys.argv[1])
		if os.path.isdir(configDir):
			config.baseConfigDir = configDir
			try:
				config.valoriServer = config.loadDir(config.baseConfigDir,hostName="config",printError = False)
			except:
				print ("Could not load config.ini from %s" % configDir)
				sys.exit()
			try:
				value = config.valoriServer['SERVER']['Blocking'].lower()
				blocking = value != "no" and value != "false"
			except KeyError:
				blocking = False
			try:
				port = int(config.valoriServer['SERVER']['Port'])
			except KeyError:
				port = 8080
			startServer(blocking= blocking,port=port)
		else:
			print ("%s is not a directory" % sys.argv[1])
			sys.exit(1)
	else:
		print ("Please provide a base directory")
		sys.exit(1)

